﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Aplicacion_Vista_AsignarMaterialesAlProyecto : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        String nomRol = (String)Session["nombreRol"];
        String nomU = (String)Session["nombreUsuario"];

        if (nomRol == null || nomRol.Length <= 0 || nomU == null || nomU.Length <= 0)
        {
            Response.Redirect("Inicio.aspx");
        }
        

        String tProy = Request.QueryString["d"];
        if (tProy == "Proyecto Social")
        {
            TextBox1.Text = "1"; //tipo
            TextBox5.Text = "1"; //idRemanetes del tipo
        }
        else
        {
            TextBox1.Text = "2"; //tipo
            TextBox5.Text = "6"; //idRemanentes del tipo
        }

        String idProy = Request.QueryString["i"];
        TextBox4.Text = idProy;

        ModeloAsignarMaterialesAlProyecto model = new ModeloAsignarMaterialesAlProyecto();
        DataTable dt1 = model.getMaterialesEstimados(idProy);
        if (dt1 == null || dt1.Rows.Count == 0)
        {
            Panel1.Visible = false;
        }

        Label7.Visible = false;

        DataTable dt2 = model.getMaterialesRemanentesEnBodega(TextBox5.Text, TextBox4.Text);
        if (dt2 == null || dt2.Rows.Count == 0)
        {
            Panel2.Visible = false;
        }

        if (!Panel1.Visible && !Panel2.Visible)
        {
            Button2.Enabled = false;
            Label7.Text = "No se encontraron materiales en la estimaci&oacute;n de materiales";
            Label7.Visible = true;
        }
        
        if (Label6.Visible)
        {
            ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
            DataTable dt = control.getMaterialesReales(idProy);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Session["materialesR"] = dt;
            Label6.Visible = false;
        }

    }
    
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Session["nombreRol"] = null;
        Session["nombreUsuario"] = null;
        Session["idRol"] = null;
        Session.Abandon();
        Response.Redirect("Inicio.aspx", true);
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        String sItem = DropDownList1.SelectedValue;
        for (int i = 0; i < DropDownList2.Items.Count; i++)
        {
            if (DropDownList2.Items[i].Value == sItem)
            {
                DropDownList2.SelectedIndex = i;
            }
        }

        for (int j = 0; j < DropDownList4.Items.Count; j++)
        {
            if (DropDownList4.Items[j].Value == sItem)
            {
                DropDownList4.SelectedIndex = j;
            }
        }

    }

    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        String sItem = DropDownList2.SelectedValue;
        for (int i = 0; i < DropDownList1.Items.Count; i++)
        {
            if (DropDownList1.Items[i].Value == sItem)
            {
                DropDownList1.SelectedIndex = i;
            }
        }
        for (int j = 0; j < DropDownList4.Items.Count; j++)
        {
            if (DropDownList4.Items[j].Value == sItem)
            {
                DropDownList4.SelectedIndex = j;
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        String idMaterial = DropDownList1.SelectedValue;
        String skuMaterial = DropDownList2.SelectedItem.Text;
        String nomMaterial = DropDownList1.SelectedItem.Text;
        String cantidadMaterial = DropDownList3.SelectedItem.Text;
        String cantidadMaterial2 = DropDownList3.SelectedItem.Text;
        String nombreBodega = DropDownList5.SelectedItem.Text;
        String idBodega = DropDownList5.SelectedValue;
        String cRemAnt = "0";
        String cantidadMaterialNuevo = cantidadMaterial;

        DataTable dt = (DataTable)Session["materialesR"];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            String idMat = dt.Rows[i].ItemArray[0].ToString();
            String idBod = dt.Rows[i].ItemArray[5].ToString();
            if (idMat == idMaterial && idBodega == idBod)
            {
                cantidadMaterial = (Int32.Parse(cantidadMaterial) + Int32.Parse(dt.Rows[i].ItemArray[3].ToString())).ToString();
                cRemAnt = dt.Rows[i].ItemArray[7].ToString();
                cantidadMaterialNuevo = (Int32.Parse(cantidadMaterial2) + Int32.Parse(dt.Rows[i].ItemArray[6].ToString())).ToString();
                dt.Rows.RemoveAt(i);
            }
        }

        DataRow r = dt.NewRow();
        r["idMaterial"] = idMaterial;
        r["skuMaterial"] = skuMaterial;
        r["nombreMaterial"] = nomMaterial;
        r["cantidadAsignada"] = cantidadMaterial;
        r["nombreBodega"] = nombreBodega;
        r["idBodega"] = idBodega;
        r["cantidadNueva"] = cantidadMaterialNuevo;
        r["cantidadRemanente"] = cRemAnt;
        dt.Rows.Add(r);
        Session["materialesR"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        DataTable dt = (DataTable)Session["materialesR"];
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        DataTable dt = (DataTable)Session["materialesR"];

        if (e.CommandName == "quitar material")
        {

            int page = GridView1.PageIndex;
            int numPages = GridView1.PageSize;
            int preindex = Int16.Parse(e.CommandArgument.ToString());
            int index = preindex + page * numPages;
            String idMaterial = dt.Rows[index]["idMaterial"].ToString();
            String idBodega = dt.Rows[index]["idBodega"].ToString();
            String cDesg = dt.Rows[index]["cantidadRemanente"].ToString();

            if (!desAsignarMaterial(idMaterial, idBodega, cDesg))
            {
                Label2.Text = "Ocurri&oacute; un error en la base de datos, Intente m&aacute;s tarde";
            }

            dt.Rows.RemoveAt(index);
            

        }


        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    
    protected void Button2_Click(object sender, EventArgs e)
    {
        DataTable dt = (DataTable)Session["materialesR"];
        String idProyecto = TextBox4.Text;
        String idRemanentes = TextBox5.Text;
        String fila = "";
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            String idMat = dt.Rows[i].ItemArray[0].ToString();
            String idBodega = dt.Rows[i].ItemArray[5].ToString();
            String cantEstimada = dt.Rows[i].ItemArray[3].ToString();
            String cantRemanentes = dt.Rows[i].ItemArray[7].ToString();
            fila = fila + idMat + ","  + idBodega + "," + idProyecto + "," + cantEstimada + "," + cantRemanentes + ";";
        }


        ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
        control.asignarMateriales(idRemanentes, idProyecto, fila, TextBox2, Response);
    }

    protected void DropDownList6_SelectedIndexChanged(object sender, EventArgs e)
    {
        ModeloAsignarMaterialesAlProyecto model = new ModeloAsignarMaterialesAlProyecto();
        Label2.Text = "";
        Button3.Enabled = true;
        String idProy = TextBox5.Text;
        String idBodega = DropDownList6.SelectedValue;
        String proyViendo = TextBox4.Text;
        DataTable dt = model.getMaterialesEnBodega(idProy, idBodega, proyViendo);
        if (dt == null || dt.Rows.Count <= 0)
        {
            Label2.Text = "No existen materiales en esta bodega";
            Label2.Visible = true;
            Button3.Enabled = false;
            return;
        }
        else
        {
            Label2.Text = "";
            Label2.Visible = false;
            Button3.Enabled = true;
            DataTable du = (DataTable)Session["BODEGA"+idBodega];
            if (du == null || du.Rows.Count <= 0)
            {
                ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
                DataTable data = control.cargarMaterialesDeBodega(idProy, idBodega, TextBox4.Text);
                Session["BODEGA" + idBodega] = data;   
                String idsBodegas = (String)Session["idsBodegas"];
                if (idsBodegas != null)
                {
                    idsBodegas = idsBodegas + idBodega + "/";
                    Session["idsBodegas"] = idsBodegas;
                }
                else
                {
                    Session["idsBodegas"] = idBodega + "/";
                }
            }
            //Response.Write((String)Session["idsBodegas"]);
            return;
        }
    }
    protected void DropDownList7_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        String sItem = DropDownList7.SelectedValue;
        for (int i = 0; i < DropDownList8.Items.Count; i++)
        {
            if (DropDownList8.Items[i].Value == sItem)
            {
                DropDownList8.SelectedIndex = i;
            }
        }

        for (int j = 0; j < DropDownList11.Items.Count; j++)
        {
            if (DropDownList11.Items[j].Value == sItem)
            {
                DropDownList11.SelectedIndex = j;
            }
        }

        ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
        String idBodega = DropDownList6.SelectedValue;
        DataTable dt = (DataTable)Session["BODEGA" + idBodega];
        
        DataTable ex = control.cantidadRestante(sItem, dt);
        if (ex != null)
        {
            DropDownList10.DataTextField = "cantidad";
            DropDownList10.DataSource = ex;
            DropDownList10.DataBind();
            DropDownList10.Enabled = true;
            Label2.Text = "";
            Button3.Enabled = true;
        }
        else
        {
            Label2.Text = "Todas las unidades de &eacute;ste material est&aacute;n asignadas";
            Button3.Enabled = false;
            DropDownList10.Enabled = false;
        }

    }
    protected void DropDownList8_SelectedIndexChanged(object sender, EventArgs e)
    {
        String sItem = DropDownList8.SelectedValue;
        for (int i = 0; i < DropDownList7.Items.Count; i++)
        {
            if (DropDownList7.Items[i].Value == sItem)
            {
                DropDownList7.SelectedIndex = i;
            }
        }
        for (int j = 0; j < DropDownList11.Items.Count; j++)
        {
            if (DropDownList11.Items[j].Value == sItem)
            {
                DropDownList11.SelectedIndex = j;
            }
        }
    }

    public bool asignarMaterial(String idMaterial, String cantidadAsignada, String idBodega)
    {

        

        DataTable materiales = (DataTable)Session["BODEGA"+idBodega];
        
        for (int i = 0; i < materiales.Rows.Count; i++)
        {
            if (materiales.Rows[i]["idMaterial"].ToString() == idMaterial)
            {
                int cantEstimada = Int32.Parse(materiales.Rows[i]["cantidadEstimada"].ToString());
                int cantAsignada = Int32.Parse(materiales.Rows[i]["cantidadAsignada"].ToString());
                int cantRestante = Int32.Parse(materiales.Rows[i]["cantidadRestante"].ToString());

                int paraAsignar = Int32.Parse(cantidadAsignada);

                if (paraAsignar > cantEstimada || cantRestante <= 0)
                {
                    return false;
                }

                if (paraAsignar <= cantRestante)
                {
                    cantAsignada = cantAsignada + paraAsignar;
                    cantRestante = cantEstimada - cantAsignada;
                    materiales.Rows[i]["cantidadAsignada"] = cantAsignada.ToString();
                    materiales.Rows[i]["cantidadRestante"] = cantRestante.ToString();
                }
            }
        }

        Session["BODEGA"+idBodega] = materiales;
        return true;
    }

    public void borraBodegasSesion(bool labelV)
    {
        
        if (labelV)
        {
            
            String idsBodegas = (String)Session["idsBodegas"];
            if (idsBodegas != null)
            {
                String[] sal = idsBodegas.Split('/');
                for (int i = 0; i < sal.Length; i++)
                {
                    DataTable dt = (DataTable)Session["BODEGA" + sal[i]];
                    if (dt != null)
                    {
                        dt = null;
                        Session["BODEGA" + sal[i]] = dt;
                    }
                }
            }
        }
        
    }

    public void init (bool labelV)
    {
        if (labelV)
        {
            
            Session["idsBodegas"] = "";
            String idBodega = DropDownList6.SelectedValue;
            String idProy = TextBox5.Text;
            DataTable du = (DataTable)Session["BODEGA"+idBodega];
            if (du == null || du.Rows.Count <= 0)
            {
                ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
                DataTable data = control.cargarMaterialesDeBodega(idProy, idBodega, TextBox4.Text);
                Session["BODEGA" + idBodega] = data;
                String idsBodegas = (String)Session["idsBodegas"];
                if (idsBodegas != null)
                {
                    idsBodegas = idsBodegas + idBodega + "/";
                    Session["idsBodegas"] = idsBodegas;
                }
                else
                {
                    Session["idsBodegas"] = idBodega + "/";
                }
            }

          
        
        }
    }

    protected void DropDownList6_DataBound(object sender, EventArgs e)
    {
        borraBodegasSesion(Label3.Visible);
        Label3.Visible = false;
        init(Label4.Visible);
        Label4.Visible = false;
    }

    protected void DropDownList7_DataBound(object sender, EventArgs e)
    {
        if (Label5.Visible)
        {
            String idMaterial = DropDownList7.SelectedValue;
            ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
            String idBodega = DropDownList6.SelectedValue;
            DataTable dt = (DataTable)Session["BODEGA" + idBodega];
           
            DataTable ex = control.cantidadRestante(idMaterial, dt);
            if (ex != null)
            {
                DropDownList10.DataTextField = "cantidad";
                DropDownList10.DataSource = ex;
                DropDownList10.DataBind();
                DropDownList10.Enabled = true;
            }
            else
            {
                Label2.Text = "No quedan unidades de &eacute;ste material";
                DropDownList10.Enabled = false;
            }
        }

        Label5.Visible = false;
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        
        String idMaterial = DropDownList7.SelectedValue;
        String skuMaterial = DropDownList8.SelectedItem.Text;
        String nomMaterial = DropDownList7.SelectedItem.Text;
        String cantidadMaterial = DropDownList10.SelectedItem.Text;
        String cantidadMaterial2 = DropDownList10.SelectedItem.Text;
        String nombreBodega = DropDownList6.SelectedItem.Text;
        String idBodega = DropDownList6.SelectedValue;
        String cNuevaAnt = "0";
        String cantidadMaterialRemanente = cantidadMaterial;


        DataTable dt = (DataTable)Session["materialesR"];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            String idMat = dt.Rows[i].ItemArray[0].ToString();
            String idBod = dt.Rows[i].ItemArray[5].ToString();
            if (idMat == idMaterial && idBodega == idBod)
            {
                cantidadMaterial = (Int32.Parse(cantidadMaterial) + Int32.Parse(dt.Rows[i].ItemArray[3].ToString())).ToString();
                cNuevaAnt = dt.Rows[i].ItemArray[6].ToString();
                cantidadMaterialRemanente = (Int32.Parse(cantidadMaterial2) + Int32.Parse(dt.Rows[i].ItemArray[7].ToString())).ToString();
                dt.Rows.RemoveAt(i);
            }
        }

        DataRow r = dt.NewRow();
        r["idMaterial"] = idMaterial;
        r["skuMaterial"] = skuMaterial;
        r["nombreMaterial"] = nomMaterial;
        r["cantidadAsignada"] = cantidadMaterial;
        r["nombreBodega"] = nombreBodega;
        r["idBodega"] = idBodega;
        r["cantidadNueva"] = cNuevaAnt;
        r["cantidadRemanente"] = cantidadMaterialRemanente;
        dt.Rows.Add(r);
        Session["materialesR"] = dt;
        GridView1.DataSource = dt;
        GridView1.DataBind();

        if (!asignarMaterial(idMaterial, cantidadMaterial2, idBodega))
        {
            Label2.Text = "Ocurri&oacute; un error en la base de datos, Intente m&aacute;s tarde";
            Label2.Visible = true;
            Button3.Enabled = false;
        }
        else
        {
            Label2.Text = "";
            Button3.Enabled = true;
            ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
            DataTable data = (DataTable)Session["BODEGA" + idBodega];

            DataTable ex = control.cantidadRestante(idMaterial, data);
            if (ex != null)
            {
                DropDownList10.DataTextField = "cantidad";
                DropDownList10.DataSource = ex;
                DropDownList10.DataBind();
                DropDownList10.Enabled = true;
                Label2.Text = "";
                Button3.Enabled = true;
            }
            else
            {
                Label2.Text = "Ha asignado todas la unidades del material";
                DropDownList10.Enabled = false;
            }
        }

    }

    public bool desAsignarMaterial(String idMaterial, String idBodega,  String cantidadDesAsignada)
    {

        try
        {

            DataTable materiales = (DataTable)Session["BODEGA" + idBodega];

            for (int i = 0; i < materiales.Rows.Count; i++)
            {
                String idMat = materiales.Rows[i]["idMaterial"].ToString();
                int cantDes = Int32.Parse(cantidadDesAsignada);
                if (idMaterial == idMat && cantDes > 0)
                {
                    int cAsignada = Int32.Parse(materiales.Rows[i]["cantidadAsignada"].ToString());
                    int cEstimada = Int32.Parse(materiales.Rows[i]["cantidadEstimada"].ToString());
                    int cRestante = Int32.Parse(materiales.Rows[i]["cantidadRestante"].ToString());

                    cAsignada = cAsignada - cantDes;
                    cRestante = cEstimada - cAsignada;

                    materiales.Rows[i]["cantidadAsignada"] = cAsignada.ToString();
                    materiales.Rows[i]["cantidadRestante"] = cRestante.ToString();
                    Session["BODEGA" + idBodega] = materiales;
                    ControladorAsignarMaterialesAlProyecto control = new ControladorAsignarMaterialesAlProyecto();
                    DataTable ex = control.cantidadRestante(idMaterial, materiales);
                    if (ex != null)
                    {
                        DropDownList10.DataTextField = "cantidad";
                        DropDownList10.DataSource = ex;
                        DropDownList10.DataBind();
                        DropDownList10.Enabled = true;
                        Label2.Text = "";
                        Button3.Enabled = true;
                    }
                    else
                    {
                        Label2.Text = "Error en la base de datos. Intente m&aacute;s tarde";
                        DropDownList10.Enabled = false;
                    }
                }
            }

            
            
            return true;
        }
        catch (Exception exc)
        {
            return false;
        }
    }
}